const router = require('koa-router')();
const { sequelize } = require('../common/dbs')

var Sequelize = require('sequelize')
var Op = Sequelize.Op;

let jwt = require('jsonwebtoken');
const menuModel = require("../models/menu")
const menuInfo = menuModel(sequelize);

const roleModel = require("../models/role")
const roleInfo = roleModel(sequelize);

function getToken(ctx) {
    let token = ctx.request.headers["authorization"]
    try {
        if (token) {
            const tokenItem = jwt.verify(token.split("Bearer ")[1], 'itliuyang')
            
            if (tokenItem) {
                return tokenItem.roleid
            }
        }
    } catch (error) {
        ctx.fail(0, error)
    }

    return ''
}

/**
 * const conditionObj = {
  [Op.or]: [
    {
      source: {
        [Op.like]: `%${text}%`
      }
    },
    {
      destination: {
        [Op.like]: `%${text}%`
      }
    },
    {
      "user.name": {
        [Op.like]: `%${text}%`
      }
    }
  ]
};

const list = await db.flights.findAndCountAll({
  where: conditionObj,
  attributes: [
    "id", "source", "destination"
  ],
  include: [
    {
      association: "user",
      attributes: ["id", "name", "mobile", "email"]
    },
  ]
});
 * 返回菜单
 * */
router.get('/nav', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;

        let roleData = await roleInfo.findOne(
            {
                where: {
                    id: getToken(ctx)
                },
            }
        );

        let whereIds = []
        roleData.menuIds.split(",").map(item => {
            whereIds.push({
                id: item
            })
        })
        let menuList = await menuInfo.findAll(
            {
                where: {
                    [Op.or]: whereIds,
                    status: 1,
                    type: 0
                },
                order: [  //排序 DESC ASC
                    ['sort', 'DESC']
                ]
            }
        );
        let newData = JSON.parse(JSON.stringify(menuList))
        menuList = initTree(newData)
        ctx.success(menuList)
        return

        ctx.success([
            {
                "id": 1000,
                "name": "文章管理",
                "url": "article/index",
                "openStyle": 0,
                "icon": "icon-barchart"
            },
            {
                "id": 1,
                "name": "系统管理",
                "url": null,
                "openStyle": 0,
                "icon": "icon-setting",
                "children": [
                    {
                        "id": 11,
                        "name": "菜单管理",
                        "url": "menu/index",
                        "openStyle": 0,
                        "icon": "icon-menu"
                    },
                    {
                        "id": 12,
                        "name": "用户管理",
                        "url": "user/index",
                        "openStyle": 0,
                        "icon": "icon-user"
                    },
                    {
                        "id": 13,
                        "name": "机构管理",
                        "url": "org/index",
                        "openStyle": 0,
                        "icon": "icon-cluster"
                    },
                    {
                        "id": 14,
                        "name": "角色管理",
                        "url": "role/index",
                        "openStyle": 0,
                        "icon": "icon-team"
                    },
                    {
                        "id": 15,
                        "name": "岗位管理",
                        "url": "post/index",
                        "openStyle": 0,
                        "icon": "icon-addteam"
                    }
                ]
            },
            {
                "id": 3,
                "name": "图表",
                "url": null,
                "openStyle": 0,
                "icon": "icon-barchart",
                "children": [
                    {
                        "id": 31,
                        "name": "堆叠面积图",
                        "url": "charts/AreaStack",
                        "openStyle": 0,
                        "icon": "icon-unorderedlist"
                    },
                    {
                        "id": 32,
                        "name": "虚线柱状图",
                        "url": "charts/CategoryStack",
                        "openStyle": 0,
                        "icon": "icon-unorderedlist"
                    },
                    {
                        "id": 33,
                        "name": "上证指数图",
                        "url": "charts/Candlestick",
                        "openStyle": 0,
                        "icon": "icon-unorderedlist"
                    }
                ]
            },
            {
                "id": 4,
                "name": "编辑器",
                "url": null,
                "openStyle": 0,
                "icon": "icon-edit",
                "children": [
                    {
                        "id": 41,
                        "name": "富文本编辑器",
                        "url": "editor/WangEditor",
                        "openStyle": 0,
                        "icon": "icon-unorderedlist"
                    },
                    {
                        "id": 42,
                        "name": "Markdown编辑器",
                        "url": "editor/MdEditor",
                        "openStyle": 0,
                        "icon": "icon-unorderedlist"
                    }
                ]
            },
            {
                "id": 5,
                "name": "界面",
                "url": null,
                "openStyle": 0,
                "icon": "icon-windows",
                "children": [
                    {
                        "id": 51,
                        "name": "Icon 图标",
                        "url": "icons/index",
                        "openStyle": 0,
                        "icon": "icon-unorderedlist"
                    },
                    {
                        "id": 52,
                        "name": "二维码生成",
                        "url": "qrcode/index",
                        "openStyle": 0,
                        "icon": "icon-unorderedlist"
                    },
                    {
                        "id": 53,
                        "name": "页面打印",
                        "url": "printJs/index",
                        "openStyle": 0,
                        "icon": "icon-unorderedlist"
                    },
                    {
                        "id": 54,
                        "name": "图片裁剪",
                        "url": "cropper/index",
                        "openStyle": 0,
                        "icon": "icon-unorderedlist"
                    },
                    {
                        "id": 55,
                        "name": "复制文本",
                        "url": "copy/index",
                        "openStyle": 0,
                        "icon": "icon-unorderedlist"
                    }
                ]
            },
            {
                "id": 10,
                "name": "多级菜单",
                "url": null,
                "openStyle": 0,
                "icon": "icon-unorderedlist",
                "children": [
                    {
                        "id": 101,
                        "name": "菜单1",
                        "url": null,
                        "openStyle": 0,
                        "icon": "icon-unorderedlist",
                        "children": [
                            {
                                "id": 1011,
                                "name": "菜单11",
                                "url": "menu/menu1/menu11/index",
                                "openStyle": 0,
                                "icon": "icon-unorderedlist"
                            },
                            {
                                "id": 1012,
                                "name": "菜单13",
                                "url": null,
                                "openStyle": 0,
                                "icon": "icon-unorderedlist",
                                "children": [
                                    {
                                        "id": 10121,
                                        "name": "菜单121",
                                        "url": "menu/menu1/menu12/menu121/index",
                                        "openStyle": 0,
                                        "icon": "icon-unorderedlist"
                                    },
                                    {
                                        "id": 10122,
                                        "name": "菜单122",
                                        "url": "menu/menu1/menu12/menu122/index",
                                        "openStyle": 0,
                                        "icon": "icon-unorderedlist"
                                    }
                                ]
                            },
                            {
                                "id": 1013,
                                "name": "菜单13",
                                "url": "menu/menu1/menu13/index",
                                "openStyle": 0,
                                "icon": "icon-unorderedlist"
                            }
                        ]
                    },
                    {
                        "id": 102,
                        "name": "菜单2",
                        "url": "menu/menu2/index",
                        "openStyle": 0,
                        "icon": "icon-unorderedlist"
                    }
                ]
            }
        ])
    } catch (err) {
        console.log(err)
        ctx.fail(0, err)
    }
})




/**
 * 编辑或者添加
 * */

router.post('/editOrAdd', async (ctx) => {
    try {
        ctx
            .validateBody("name")
            .required("菜单名称不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("type")
            .required("类型不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("url")
            .required("路由不能为空")
            .isString()
            .trim()

        let reqBody = ctx.request.body;
        let requestData = null
        let msgType = '添加'
        let b = {
            name: reqBody.name,
            type: reqBody.type,
            pid: reqBody.pid,
            status: reqBody.status,
            icon: reqBody.icon,
            url: reqBody.url,
            authority: reqBody.authority,
            status: reqBody.status || 1,
        }

        if (reqBody.id) {
            delete b.id
            // 编辑
            requestData = await menuInfo.update(b, {
                where: {
                    id: reqBody.id
                }
            })
            msgType = '修改'
        } else {
            // 新增
            requestData = await menuInfo.create(b)
        }
        if (requestData) {
            ctx.success(msgType + '成功')
        } else {
            ctx.fail(0, msgType + '失败')
        }

    } catch (err) {
        ctx.fail(0, err && err.message)
    }
})

/**
 * 详情
 * */

router.get('/detail', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        if (!reqQuery.id) {
            ctx.fail(0, 'id不能为空')
        }
        let cardData = await menuInfo.findOne(
            {
                where: {
                    id: reqQuery.id
                },
            }
        );

        if (cardData) {
            ctx.success(cardData)
        } else {
            ctx.fail(0, '内容已删除,或者不存在')
        }
    } catch (err) {
        ctx.fail(0, err)
    }
})



// 查询按钮权限列表
router.get('/authority', async (ctx) => {
    try {
        let roleData = await roleInfo.findOne(
            {
                where: {
                    id: getToken(ctx)
                },
            }
        );

        let whereIds = []
        roleData.menuIds.split(",").map(item => {
            whereIds.push({
                id: item
            })
        })
        let menuList = await menuInfo.findAll(
            {
                where: {
                    [Op.or]: whereIds,
                    status: 1,
                    type: 1
                },
                order: [  //排序 DESC ASC
                    ['sort', 'DESC']
                ]
            }
        );
        menuList = menuList.map(item => {
            return item.authority
        })
        ctx.success(menuList)
    } catch (err) {
        ctx.fail(0, err)
    }
})
// 查询列表
router.get('/list', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        let reData = await menuInfo.findAll(
            {
                where: {
                    status: 1
                },
                order: [  //排序 DESC ASC
                    ['sort', 'DESC']
                ]
            }
        );
        let newData = JSON.parse(JSON.stringify(reData))
        reData = initTree(newData)

        ctx.success(reData)
    } catch (err) {
        ctx.fail(0, err)
    }
})
// 查询分页列表
router.get('/pageList', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        let reData = await menuInfo.findAndCountAll(
            {
                order: [  //排序 DESC ASC
                    ['created_at', 'DESC']
                ],
                limit: reqQuery.limit ? parseInt(reqQuery.limit) : 10,
                offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0
            }
        );

        let newData = JSON.parse(JSON.stringify(reData.rows))
        reData.rows = initTree(newData)
        ctx.success(reData)
    } catch (err) {
        ctx.fail(0, err)
    }
})
/**
 * 生成tree
 * @param parent_id 父id
 */
const initTree = (jsonArray, parent_id = 0) => {
    // jsonArray 变量数据
    // 第一次以后：根据id去查询parent_id相同的（相同为子数据）
    // 第一次：查找所有parent_id为0的数据组成第一级
    const children = jsonArray.filter(item => item.pid == parent_id)
    // // 第一次：循环parent_id为0数组
    return children.map(item => ({
        ...item,
        // 当前存在id（id与parent_id应该是必须有的）调用initTree() 查找所有parent_id为本id的数据
        // childs字段写入
        children: initTree(jsonArray, item.id)
    }))
}



// 删除
router.delete('/del/:id', async (ctx) => {
    try {
        if (!ctx.params.id) {
            ctx.fail(0, 'id不能为空')
        }
        let requestData = await menuInfo.destroy({
            where: {
                id: ctx.params.id
            }
        })
        if (requestData > 0) {
            ctx.success('删除成功')
        } else {
            ctx.fail(0, '内容已删除,或者不存在')
        }
    } catch (err) {
        ctx.fail(0, err)
    }
})

module.exports = router.routes();




